import React, { useEffect, useState, useRef } from 'react';
import 'jsmind/style/jsmind.css';
import jsMind from 'jsmind/js/jsmind';
import { searchApi } from '@/request/gitlab';
import { getEnvUnionApi } from '@/request/story';
import menuDefine from '@/utils/jsmind.menu';
import { renderMind, options } from '@/utils/config/mindConfig';
import { env } from '@/utils/data';

interface TreeChild {
  id: string;
  topic: string;
  branch: string;
  developer: string;
  [propName: string]: any;
}

// 返回环境名称
const env_name = (value) => {
  const res = env.filter((item) => item.value === value)[0];
  if (res) {
    return res.label;
  }
  return '未选择环境';
};

// 随机生成左右
const directive = () => (Math.random() > 0.5 ? 'left' : 'right');

const Mind = () => {
  const [jms, setJm] = useState<any>(null);
  const [mH, setMH] = useState<any>(null);
  const jm: any = useRef(null);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      setMH(window.innerHeight - 220);
    }
  }, []);

  // 生成树形
  const writeMind = (treeData) => {
    // eslint-disable-next-line new-cap
    jm.current = new jsMind(options);
    // 让 jm 显示这个 mind 即可
    jm.current.show(treeData);
    setJm(jm.current);
    if (typeof window !== 'undefined') {
      window.jsmind = jsMind;
    }
    menuDefine(window, 'jsmind');
  };

  // 2、所有需求使用 项目、环境、分支 数据
  const envs = (storys, projects) => {
    const obj = projects;
    for (let i = 0; i < storys.length; i += 1) {
      const { relation_env, project_name } = storys[i];
      if (relation_env) {
        const keys = Object.keys(relation_env);
        for (let j = 0; j < keys.length; j += 1) {
          if (obj[project_name]) {
            obj[project_name][keys[j]] = relation_env[keys[j]];
          }
        }
      }
    }
    return obj;
  };
  // 3、所有项目 生成6个环境
  const envs2 = (projects) => {
    const obj = {};
    for (let i = 0; i < projects.length; i += 1) {
      const { name, envs: projectEnv } = projects[i];
      obj[name] = {};
      for (let j = 0; j < projectEnv.length; j += 1) {
        obj[name][projectEnv[j]] = {};
      }
    }
    return obj;
  };
  // 获取所有的项目。
  const getProjectList = async () => {
    const res: any = await searchApi({ showInMind: 1 });
    if (res) {
      return res;
    }
    return [];
  };

  // const zoomIn = () => {
  //   jm.current.view.zoomIn();
  // };
  // const zoomOut = () => {
  //   jm.current.view.zoomOut();
  // };
  // const getSelectNode = () => {
  //   const node = jms.get_selected_node();
  // };

  // 递归生成children
  const createChild = (data: TreeChild[], project_name: string) => {
    if (data.length === 0) return [];
    const res: any = [];
    for (let i = 0; i < data.length; i += 1) {
      const obj = {
        ...data[i],
        id: `${project_name}$${data[i].branch}`,
        topic: data[i].branch,
        // 开发人员
        children: [
          {
            id: `${project_name}$${data[i].branch}$${data[i].developer}`,
            topic: data[i].developer,
          },
        ],
      };
      res.push(obj);
    }
    return res;
  };

  const handleChild = (data, project_name: string) => {
    let obj: any = [];
    if (data.isMergeBranch) {
      obj.push({
        id: `${project_name}$${String(data.branch)}`,
        topic: data.branch,
        children: createChild(data.children, project_name),
      });
    } else if (data.branch) {
      obj = [
        {
          id: `${project_name}$${String(data.branch)}`,
          topic: data.branch,
          children: [
            {
              id: `${project_name}$${data.branch as string}$${data.developer as string}`,
              topic: data.developer,
            },
          ],
        },
      ];
    }
    return obj;
  };

  // 生成树形数据
  const createTreeData = (data) => {
    const res: any = [];
    Object.keys(data).forEach((item) => {
      const obj = {
        id: item,
        topic: item,
        direction: directive(),
        expanded: true,
        children: [] as any,
      };
      Object.keys(data[item]).forEach((k) => {
        // key是环境
        obj.children.push({
          id: `${item}${k}`,
          topic: env_name(k),
          expanded: true,
          // 默认只有每个项目每个环境一个分支
          // item 项目名称
          children: handleChild(data[item][k], item),
        });
      });
      res.push(obj);
    });
    return res;
  };

  // 获取项目关联环境
  const handleGetEnv = async () => {
    const res = await getEnvUnionApi({});
    if (res) {
      return Promise.resolve(res);
    }
    return Promise.resolve([]);
  };

  const handleData = async () => {
    // 2、获取所有的项目
    const projectRes = await getProjectList();
    const curProjectEnv = envs2(projectRes);
    // 1、所有需求使用 项目、环境、分支 数据
    // const storyRes = await getStoryList();
    const storyRes = await handleGetEnv();
    const curEnvUsed = envs(storyRes, curProjectEnv);
    // 3、生成结构
    const treeData = createTreeData(curEnvUsed);
    // 4、生成树
    writeMind(renderMind(treeData));
  };

  useEffect(() => {
    // writeMind();
    // getStoryList();
    // getProjectList();
    handleData();
  }, []);

  const handleClick = (e) => {
    console.log(jms.get_selected_node());
  };

  return (
    <div>
      {/* <div onClick={() => zoomIn()}>放大</div>
      <div onClick={() => zoomOut()}>缩小</div>
      <div onClick={() => getSelectNode()}>获取选中的节点</div> */}
      <div id="jsmind_container" style={{ width: '100%', height: mH || '80vh' }} onClick={handleClick}></div>
    </div>
  );
};

export default Mind;
